package com.yanqu.road.server.cmd.union.parergon;

import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.entity.union.UnionInfo;
import com.yanqu.road.entity.union.parergon.UnionParergonOperateResult;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.pb.union.Parergon;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.union.UnionParergonModule;
import com.yanqu.road.server.manger.config.UnionConfigMgr;
import com.yanqu.road.server.manger.union.UnionMgr;
import com.yanqu.road.server.manger.union.UnionParergonMgr;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.string.StringUtils;

//@Cmd(code = Protocol.S_UNION_PARERGON_OPERATE, desc = "点击经营")
public class OperateCmd extends AbstractCommand {

    private int parergonId;

    private int type;

    private int operateTimes;

    private UnionParergonOperateResult operateResult;

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        Parergon.OperateReqMsg reqMsg = Parergon.OperateReqMsg.parseFrom(packet.getBytes());
        parergonId = reqMsg.getParergonId();
        type = reqMsg.getType();
        operateTimes = reqMsg.getOperateTimes();
        return true;
    }

    @Override
    public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
        UnionParergonModule unionParergonModule = player.getModule(UnionParergonModule.class);
        if(0 == type){
            operateResult = unionParergonModule.operate(parergonId);
        }else{
            UserInfo userInfo = player.getUserInfo();
            String unionUid = userInfo.getUnionUid();
            if (StringUtils.isNullOrEmpty(unionUid)) {
                operateResult.setRet(GameErrorCode.E_PARERGON_NOT_IN_UNION);
                return;
            }
            UnionInfo unionInfo = UnionMgr.getUnionInfo(unionUid);
            int unionLevel = UnionConfigMgr.getUnionLv(unionInfo.getExperience());
            if(GameConfig.PARERGON_ONE_KEY_OPERATE_UNION_LV > unionLevel){
                operateResult.setRet(GameErrorCode.E_UNION_LEVEL_NO_ENOUGH);
                return ;
            }
            unionParergonModule.calOperateTimes();
            operateResult = unionParergonModule.oneKeyOperate(parergonId, operateTimes);
        }

    }

    @Override
    public void sendData(GamePlayer player) {
        player.sendPacket(Protocol.U_UNION_PARERGON_OPERATE, UnionParergonMgr.builderOperateRespMsg(operateResult));
    }

}
